<?php

    define("SOCKET_TCP",1);
    define("SOCKET_UDP",2);

    class CClientSocket
    {
	var $m_hSocket;
    
	static function &GetInstance()
	{
	    global $g_hObjects;
	    static $m_hApp = NULL;
					 
	    if(!isset($m_hApp))
	    {
		$m_hApp = new CClientSocket();
		$g_hObjects[] = $m_hApp;
		$m_hApp->OnInit();
						
	    }
	    
	    return $m_hApp;
	}
	
	function OnInit()
	{
	}
	
	function OnDestroy()
	{
	    $this->Close();
	}
	
	
	function Connect($iProtocol,$szAddress,$iPort)
	{
	    if($iProtocol == SOCKET_TCP)
	    {
		$this->m_hSocket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
	    }
	    else if($iProtocol == SOCKET_UDP)
	    {
		$this->m_hSocket = socket_create(AF_INET,SOCK_STREAM,SOL_UDP);
	    }
	    
	    if($this->m_hSocket == false)
	    {
		echo "blad podczas tworzenia gniazda :( <br/>;";
		return false;
	    }
	
	    $szIp = gethostbyname($szAddress);
	    
	    if(socket_connect($this->m_hSocket,$szIp,$iPort) == false)
	    {
		echo "nie moglem sie polaczyc :( <br/>";
		return false;
	    }
	    
	    //socket_set_nonblock($this->m_hSocket);
	    
	    return true;
	} 
	
	function Read($iMaxLen)
	{
	    return socket_read($this->m_hSocket,$iMaxLen,PHP_BINARY_READ);
	}
	
	function Write($szString,$iLen = 0)
	{
	    if($iLen == 0)
	    {
		return socket_write($this->m_hSocket,$szString);
	    }
	    else
	    {
		return socket_write($this->m_hSocket,$szString,$iLen);
	    }
	}
	
	function Close()
	{
	    //socket_shutdown($this->m_hSocket,2);
	    socket_close($this->m_hSocket);		
	}
    }

?>